package cn.zglbk.utils.proto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/6/18 12:49
 * 描述：
 */
public class ProtoUtils {
    public static void main(String[] args) {
//        CreateEntity buildPath = new CreateEntity();
//        buildPath.setScanPackages0("cn.gf.nn");
//        buildPath.setDtoName("IoPojo");
//        buildPath.setCsProxyPath("E:\\project\\Client\\gf-nn\\Assets\\Scripts\\IoPojo\\Proxy\\");
//
//        buildPath.setCsDtoPath("E:\\project\\server\\gf-nn\\Protobufs\\CSharpProtoc\\Proto\\");
//        buildPath.setJvDtoPath("E:\\project\\server\\gf-nn\\Protobufs\\JavaProtoc\\");
//
//        buildPath.setJvProxyPath("E:\\project\\server\\gf-nn\\gf-nn-game\\src\\main\\java\\cn\\gf\\nn\\build\\jv\\");
//        buildPath.setJvDtoPacket("cn.gf.nn.pojo.proto");
//        JnettyProxyCreateBuild.iocLoader(buildPath);
//        JnettyDtoCreateBuild.iocLoader(buildPath);
//        String cmd = "@tool\\protoc.exe --proto_path=E:/project/server/gf-nn/Protobufs/CSharpProtoc/Proto/ IoPojo.proto --csharp_out=E:\\project\\Client\\gf-nn\\Assets\\Scripts\\IoPojo\\Dto";
//        WorkerEntity entity = new WorkerEntity();
//        entity.setCmd(cmd);
//        entity.setCreateBarName("build.bat");
//        entity.setEncoding("GBK");
//        entity.setWorkerPath("E:\\project\\server\\gf-nn\\Protobufs\\CSharpProtoc\\");
//        ExecUtil.builder(entity);
//        cmd = "protoc --java_out=E:\\project\\server\\gf-nn\\gf-nn-game\\src\\main\\java ./IoPojo.proto";
//        entity.setCmd(cmd);
//        entity.setWorkerPath("E:\\project\\server\\gf-nn\\Protobufs\\JavaProtoc\\");
//        ExecUtil.builder(entity);
    }
    public static void builder(WorkerEntity entity){
        excuteCMDBatFile(entity);
    }
    private static Logger logger = LoggerFactory.getLogger(ProtoUtils.class);
    private static boolean writeFile(File exportFile, final String content) {
        if (exportFile == null || StringUtils.isEmpty(content)) {
            return false;
        }
        if (!exportFile.exists()) {
            try {
                exportFile.getParentFile().mkdirs();
                exportFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("创建本地json文件异常: " + e.getMessage());
                return false;
            }
        }

        BufferedWriter bufferedWriter = null;
        try {
            FileOutputStream os = new FileOutputStream(exportFile);
            FileDescriptor fd = os.getFD();

            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            bufferedWriter.write(content);
            bufferedWriter.flush();

            //been written to disk.
            fd.sync();
        } catch (UnsupportedEncodingException e) {
            logger.error("saveDBData#catch an UnsupportedEncodingException (" + e.getMessage() + ")");
            return false;
        } catch (FileNotFoundException e) {
            logger.error("saveDBData#catch an FileNotFoundException (" + e.getMessage() + ")");
            return false;
        } catch (IOException e) {
            logger.error("saveDBData#catch an IOException (" + e.getMessage() + ")");
            return false;
        } catch (Exception e) {
            logger.error("saveDBData#catch an exception (" + e.getMessage() + ")");
            return false;
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                    bufferedWriter = null;
                }
            } catch (IOException e) {
                logger.error("writeJsonToFile#catch an exception (" + e.getMessage() + ")");
            }
        }
        return true;
    }

    private static boolean excuteCMDBatFile(WorkerEntity entity) {
        final String METHOD_NAME = "excuteCMDBatFile#";
        boolean result = true;
        Process p;
//        File batFile = new File("E:\\Protobufs\\protobuf\\test.bat");
        File batFile = new File(entity.getWorkerPath() + entity.getCreateBarName());
        System.out.println(batFile.getAbsolutePath());
        boolean isSuccess = writeFile(batFile, entity.getCmd());
        if (!isSuccess) {
            logger.error(METHOD_NAME + "write cmd to File failed.");
            return false;
        }

        logger.info("工作目录:" + entity.getWorkerPath());
        try {
            p = Runtime.getRuntime().exec(entity.getWorkerPath() + entity.getCreateBarName(), null, new File(entity.getWorkerPath()));
            InputStream fis = p.getErrorStream();
            //encoding = System.getProperty("file.encoding")
            InputStreamReader isr = new InputStreamReader(fis,entity.getEncoding());
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            p.waitFor();
            int i = p.exitValue();
            logger.info(METHOD_NAME + "exitValue = " + i);
            if (i != 0) {
                result = false;
                logger.error(METHOD_NAME + "excute cmd failed, [result = " + result + ", error message = " + builder.toString() + "]");
            } else {
                logger.debug(METHOD_NAME + "excute cmd result = " + result);
            }
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
            logger.error(METHOD_NAME + "fail to excute bat File [ErrMsg=" + e.getMessage() + "]");
        }

        return result;
    }
}
